<template>
  <div class="parent">
    <div class="title mb-50">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/zhinengyewu/library' }">{{
          $t("route.renxiangkuguanli")
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ lib_name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="divider"></div>
    <div class="content">
      <div class="header">
        <MyButton
          class="mr-10 import"
          icon="el-icon-upload2"
          @click="handleImportSingle"
          >{{ $t("common.importSingle") }}</MyButton
        >
        <el-dropdown class="mr-20" trigger="click">
          <MyButton class="import" icon="el-icon-upload2">{{
            $t("common.importBatch")
          }}</MyButton>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <el-upload
                :action="''"
                :accept="'image/jpeg,image/png,image/bmp,image/tiff'"
                :show-file-list="false"
                multiple
                :http-request="handleUpload"
              >
                {{ $t("common.selectFile") }}
              </el-upload>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-upload
                ref="uploadDictory"
                :action="''"
                :http-request="handleUpload"
                :show-file-list="false"
                :before-upload="beforeUpload"
                multiple
              >
                {{ $t("common.selectDictory") }}
              </el-upload>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <MyButton
          className="export"
          icon="el-icon-download"
          @click="handleExportAll"
        >
          {{ $t("common.allExport") }}</MyButton
        >
        <MyButton
          className="export"
          icon="el-icon-download"
          @click="handleExport"
        >
          {{ $t("common.export") }}</MyButton
        >
        <MyButton
          className="delete"
          icon="el-icon-delete"
          @click="handleDeleteMultiple"
          >{{ $t("common.multipleDelete") }}</MyButton
        >
        <MyButton class="add">
          <el-checkbox
            v-model="checkedAll"
            :indeterminate="isIndeterminate"
            @change="handleSelectAll"
            >{{ $t("common.selectAll") }}</el-checkbox
          ></MyButton
        >
      </div>
      <div class="card-wrapper mt-20 d-flex jc-start ai-start">
        <Card
          class="mr-20 mb-20"
          v-for="(item, index) in cardList"
          :key="index"
          :cardData="item"
          @click.native="handleSelect(item)"
          @dblclick.native="handleShowDetail(item)"
        />
        <NoData v-if="cardList.length === 0" />
      </div>
      <Pagination
        v-show="total_num > 10"
        :total="total_num"
        :page.sync="pageNumber"
        :limit.sync="qry_len"
        class="pagingStyle"
        @pagination="getStaffList()"
      />
    </div>
    <ImportSingle
      :visible.sync="isImportSingleVisible"
      :lib_id="lib_id"
      @refresh="getStaffList"
    />
    <SingleExportDialog
      :zippasswd.sync="zippasswd"
      @confirm="confirmSingle"
      @cancel="cancelSingle"
      :visible.sync="isSingleExportShow"
      :step="singleStep"
    />
    <MultipleExportDialog
      :zippasswd="zippasswd"
      :num="total_num"
      @confirm="confirmBatch"
      @cancel="cancelBatch"
      :visible.sync="isBatchExportShow"
      :step="batchStep"
    />
    <BatchUploadPromit
      :visible.sync="isShowBatchUpload"
      :percent="uploadProgress"
      :batchInfo="batchInfo"
    />
    <StaffDetail
      :visible.sync="isDetailShow"
      :row="row"
      @refresh="getStaffList"
    />
  </div>
</template>

<script>
import MyButton from "@/components/Button";
import ImportSingle from "./ImportSingle";
import {
  getStaffList,
  deleteStaffList,
  exportStaffList,
  exportBatchStaffList,
  uploadFileBatch,
} from "./service";
import Card from "./Card";
import util from "@/utils";
import { validatePwd, downLoadUrl } from "@/services";
import SingleExportDialog from "@/components/SingleExportDialog.vue";
import MultipleExportDialog from "@/components/MultipleExportDialog.vue";
import BatchUploadPromit from "./BatchUploadPromit.vue";
import _ from "lodash";
import StaffDetail from "./StaffDetailEdit.vue";
import Pagination from "@/components/Pagination";
import { getStorageTime } from "@/views/storage/service.js";
export default {
  components: {
    MyButton,
    ImportSingle,
    Card,
    SingleExportDialog,
    MultipleExportDialog,
    BatchUploadPromit,
    StaffDetail,
    Pagination,
  },
  data() {
    return {
      lib_name: "",
      lib_id: "",
      checkedAll: false,
      isImportSingleVisible: false,
      cardList: [],
      isIndeterminate: false,
      isSingleExportShow: false,
      isBatchExportShow: false,
      zippasswd: "",
      singleStep: 0,
      batchStep: 0,
      isShowBatchUpload: false,
      uploadProgress: 0,
      batchInfo: {
        total: 0,
        err_count: 0,
      },
      fileList: [],
      isDetailShow: false,
      row: {},
      qry_len: 50,
      pageNumber: 1,
      total_num: 0,
    };
  },
  watch: {
    cardList: {
      handler(val) {
        let allChecked = true;
        let allNoChecked = true;
        val.forEach((item) => {
          if (!item.isSelect) {
            allChecked = false;
          } else {
            allNoChecked = false;
          }
        });
        this.checkedAll = allChecked;
        this.isIndeterminate = !allNoChecked && !allChecked;
      },
      deep: true,
    },
  },
  computed: {
    selectedList() {
      return this.cardList.filter((item) => item.isSelect);
    },
    start_no: {
      get() {
        return 1 + this.qry_len * (this.pageNumber - 1);
      },
    },
  },
  async mounted() {
    const params = this.$route.query;
    if (params) {
      this.lib_name = params.lib_name;
      this.lib_id = Number(params.lib_id);
      await this.getStorageTime();
      this.getStaffList();
    }
    this.throttleUploadFileList = _.throttle(this.uploadFileList, 500, {
      leading: false,
    });
    this.$refs.uploadDictory.$children[0].$refs.input.webkitdirectory = true;
  },
  methods: {
    async getStorageTime() {
      const params = {
        store_obj: 1,
      };
      const res = await getStorageTime(params);
      if (res.code == 0) {
        this.saved_time = res.data.saved_time;
      }
      return true;
    },
    handleShowDetail(item) {
      // 显示人脸详情
      this.isDetailShow = true;
      this.row = { ...item };
    },
    beforeUpload(file) {
      console.log("file", file);
      if (!this.isValidImageType(file.type) || !file.type) {
        return false;
      }
    },
    // 检查文件类型是否符合要求
    isValidImageType(type) {
      const validTypes = ["image/jpeg", "image/png", "image/bmp", "image/tiff"];
      return validTypes.includes(type);
    },
    handleUpload(data) {
      this.fileList.push(data.file);
      this.throttleUploadFileList();
    },
    async uploadFileList() {
      const obj = {};
      this.fileList.map((file, index) => {
        obj[`img_${index + 1}`] = file;
      });
      const params = {
        lib_id: this.lib_id,
        uuid: util.generateUUID(),
        ...obj,
      };
      try {
        const res = await uploadFileBatch(params);
        if (res.code === 0) {
          this.isShowBatchUpload = true;
          this.$set(this.batchInfo, "total", this.fileList.length);
          this.$set(this.batchInfo, "err_count", res.data.err_count);
          this.$set(this.batchInfo, "url", res.data.url);
          this.progressAnimation();
          this.getStaffList();
        }
      } finally {
        this.fileList = [];
      }
    },
    progressAnimation() {
      const timer = setInterval(() => {
        this.uploadProgress += 10;
        if (this.uploadProgress >= 100) {
          this.uploadProgress = 100
          clearInterval(timer);
        }
      }, 20);
    },
    async getStaffList() {
      const params = {
        lib_id: this.lib_id,
        qry_len: this.qry_len,
        start_no: this.start_no,
      };
      const res = await getStaffList(params);
      this.cardList = res.data.record.map((item) => {
        return {
          ...item,
          saved_time: this.saved_time,
        };
      });
      this.total_num = res.data.total_num;
    },
    handleImportSingle() {
      this.isImportSingleVisible = true;
    },
    handleExportAll() {
      this.isBatchExportShow = true;
    },
    handleExport() {
      if (!this.selectedList.length) {
        this.$message.warning(this.$t("face_noChoose"));
        return;
      }
      this.isSingleExportShow = true;
    },
    async confirmSingle(form) {
      if (this.singleStep === 1) {
        this.isSingleExportShow = false;
        this.zippasswd = "";
        this.singleStep = 0;
        return;
      } else {
        const { curuser_pwd } = form;
        const res = await validatePwd({ userpasswd: curuser_pwd });
        if (res.code === 0) {
          const params = {
            img_ids: this.selectedList.map((item) => item.img_id).join(","),
            lib_id: this.lib_id,
          };
          const res = await exportStaffList(params);
          this.singleStep = 1;
          this.zippasswd = res.data.zippasswd;
          downLoadUrl(res.data.export_url);
        }
      }
    },
    cancelSingle() {
      this.singleStep = 0;
      this.zippasswd = "";
    },
    cancelBatch() {
      this.batchStep = 0;
      this.zippasswd = "";
    },
    async confirmBatch(form) {
      // 验证密码
      if (this.batchStep === 0) {
        const { curuser_pwd } = form;
        const res = await validatePwd({ userpasswd: curuser_pwd });
        if (res.code === 0) {
          this.batchStep = 1;
        }
      } else {
        const params = {
          lib_id: this.lib_id,
          ...form,
        };
        const res = await exportBatchStaffList(params);
        if (res.code === 0) {
          this.zippasswd = res.data.zippasswd;
          downLoadUrl(res.data.export_url);
        }
      }
    },
    handleDeleteMultiple() {
      if (!this.selectedList.length) {
        this.$message.warning(this.$t("face_noChoose"));
        return;
      }
      this.$confirm(
        this.$t('face_batchDelete',{num:this.selectedList.length}),
        this.$t('batchDelete'),
        {
          confirmButtonText: this.$t('makeSure2'),
          cancelButtonText: this.$t('cancel'),
          type: "warning",
        }
      ).then(async () => {
        const params = {
          img_ids: this.selectedList.map((item) => item.img_id).join(","),
          lib_id: this.lib_id,
        };
        const res = await deleteStaffList(params);
        if (res.code === 0) {
          util.msg.success("deleteSuccess");
          this.getStaffList();
        }
      });
    },
    handleSelect(item) {
      this.$set(item, "isSelect", !item.isSelect);
    },
    handleSelectAll(val) {
      this.cardList.forEach((item) => {
        this.$set(item, "isSelect", val);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.parent {
  font-size: 14px;
  height: 100%;
  background: #ffffff;
  border-radius: 20px;
  width: 100%;
  padding: 20px;
  .title {
  }
  .content {
    .card-wrapper {
      flex-wrap: wrap;
    }
  }
  .divider {
    width: 100%;
    height: 2px;
    background-color: rgba(217, 222, 229, 1);
    margin-top: 30px;
    margin-bottom: 30px;
    flex-shrink: 0;
  }
}
</style>
